﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using DevExpress.XtraEditors;
using FileManager_Client.BusinessLogic;
using FileManager_Client.BusinessLogic.FileManagerUserService;
using FileManager_Client.BusinessLogic.FileTransferService;
using FileManager_Client.Utility;
using Newtonsoft.Json;

namespace FileManager_Client.PresentationLayer
{
    public partial class UploadTask : Form
    {
        private string[] uploadFilePath;
        private FolderResult folderResult;
        private ToolStripStatusLabel toolStripStatusLabel;
        private UserLoginResult userSession;
        private ServerFiles serverFiles;
        public UploadTask(string[] uploadFilePathColletion, FolderResult parentFolderResult, ToolStripStatusLabel toolStripStatusLabelParent,ServerFiles parentForm)
        {
            InitializeComponent();
            uploadFilePath = uploadFilePathColletion;
            folderResult = parentFolderResult;
            toolStripStatusLabel = toolStripStatusLabelParent;
            skinEngine1.SkinFile = "office2007.ssk";
            StartPosition = FormStartPosition.CenterScreen;
            toolStripStatusLabel.Text = string.Format("{0}个上传任务;", uploadFilePath.Length);
            toolStripStatusLabel.Tag = uploadFilePath.Length;
            serverFiles = parentForm;
            userSession = CacheGlobal.GetCache(GlobalString.System_Config_String.UserSession) as UserLoginResult;
        }

        private void UploadTask_Shown(object sender, EventArgs e)
        {
            try
            {
                var willDelete = new List<string>();
                foreach (var temp in uploadFilePath)
                {
                    var listView = serverFiles.Controls.Find("lvFileView", true).FirstOrDefault() as ListView;
                    var hasFile = false;
                    var fileInfo = new System.IO.FileInfo(temp);
                    foreach (var item in listView.Items.Cast<ListViewItem>().Where(item => item.Text.Equals(fileInfo.Name)))
                        hasFile = true;
                    if (!hasFile) continue;
                    var message = string.Format("服务器已包含 {0} 文件，是否覆盖?", fileInfo.Name);
                    if (XtraMessageBox.Show(message, GlobalString.System_Config_String.MbxInfoStr, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                        willDelete.Add(temp);
                }
                foreach (var deleteFile in willDelete)
                    uploadFilePath.ToList().Remove(deleteFile);
                if (uploadFilePath.Length <= 0) return;
                var backgroundWorker = new BackgroundWorker();
                backgroundWorker.DoWork += backgroundWorker_DoWork;
                backgroundWorker.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                LogLoader.Instance.Log.Error("UploadTask_Shown has problem", ex);
                XtraMessageBox.Show("上传失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
    //        try
    //        {
    //            var wcf_FileTransferService =
    //CacheGlobal.GetCache(GlobalString.System_Config_String.Wcf_FileTransferServiceCacheKey) as
    //FileTransfer_ServiceClient;
    //            if (wcf_FileTransferService.State != CommunicationState.Opened)
    //                wcf_FileTransferService.Open();
                
    //            foreach (var temp in uploadFilePath)
    //            {
    //                var fileInfo = new System.IO.FileInfo(temp);
    //                using (var stream = new System.IO.FileStream(temp, System.IO.FileMode.Open, System.IO.FileAccess.Read))
    //                {
    //                    using (var uploadStreamWithProgress = new StreamWithProgress(stream))
    //                    {
    //                        uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged;
    //                        Invoke((EventHandler)delegate
    //                        {
    //                            lb_FileDynamicName.Text = fileInfo.Name;
    //                        });
    //                        // upload file
    //                      //  wcf_FileTransferService.UploadFile(fileInfo.Name, folderResult.FileSidk__BackingField, fileInfo.Length, userSession.UserIdk__BackingField, uploadStreamWithProgress);
    //                        //fileInfo.Name, folderResult.FileSidk__BackingField, fileInfo.Length, userSession.UserIdk__BackingField
    //                        var fileAttchInfo = new FileAttchInfo
    //                                                {
    //                                                    FileName = fileInfo.Name,
    //                                                    FolderId = folderResult.FileSidk__BackingField,
    //                                                    Length = fileInfo.Length,
    //                                                    UserId = userSession.UserIdk__BackingField
    //                                                };
    //                        var jsonData = JsonConvert.SerializeObject(fileAttchInfo);
    //                        wcf_FileTransferService.UploadFile(jsonData, uploadStreamWithProgress);
    //                        // close service client
    //                        Invoke((EventHandler)delegate
    //                        {
    //                            toolStripStatusLabel.Text = string.Format("{0}个上传任务;", ((int)toolStripStatusLabel.Tag) - 1);
    //                        });
    //                    }
    //                }
    //            }
    //            serverFiles.Invoke((EventHandler) delegate
    //                                                  {
    //                                                      serverFiles.UpdateListView(folderResult.FileSidk__BackingField);
    //                                                  });
    //            isClose = true;
    //            Invoke((EventHandler)delegate
    //            {
    //                Close();
    //            });
    //            GC.Collect();
    //        }
    //        catch (Exception ex)
    //        {
    //            LogLoader.Instance.Log.Error("backgroundWorker_DoWork has problem", ex);
    //            Invoke((EventHandler)delegate
    //            {
    //                toolStripStatusLabel.Text = string.Format("{0}个上传任务;", 0);
    //            });
    //            XtraMessageBox.Show("上传失败!", GlobalString.System_Exception_String.MbxErrorStr, MessageBoxButtons.OK, MessageBoxIcon.Error);
    //            isClose = true;
    //            Invoke((EventHandler)delegate
    //            {
    //                Close();
    //            });
    //            GC.Collect();
    //        }

        }

        private bool isClose;
        private void UploadTask_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!isClose)
                e.Cancel = true;
            Invoke((EventHandler) delegate
                                      {
                                          toolStripStatusLabel.Text = string.Format("{0}个上传任务;", 0);
                                      });
        }

        void uploadStreamWithProgress_ProgressChanged(object sender, StreamWithProgress.ProgressChangedEventArgs e)
        {
            if (e.Length != 0)
                pb_Upload.Invoke((EventHandler)delegate
                {
                    pb_Upload.Value = (int)(e.BytesRead * 100 / e.Length);
                });
        }
    }

    public class FileAttchInfo
    {
        public string FileName { get; set; }
        public string UserId { get; set; }
        public string FolderId { get; set; }
        public long Length { get; set; }
    }

    public class DownlaodAttchInfo
    {
        public string FileName { get; set; }
        public long Length { get; set; }
    }
}
